package com.boomsecret.juc.executor;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author wangjinliang on 2019/1/22.
 */
public class ForkJoinPoolDemo {
    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinSumTask forkJoinTask = new ForkJoinSumTask(1, 1000);
        ForkJoinTask<Integer> result = forkJoinPool.submit(forkJoinTask);
        try {
            System.out.println("start");
            System.out.println(result.get());
            System.out.println("end");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("main end");
    }

    public static class ForkJoinSumTask extends RecursiveTask<Integer> {
        private static final int SIZE = 2;
        private int start;
        private int end;

        public ForkJoinSumTask(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        protected Integer compute() {
            int sum = 0;
            if (end - start <= SIZE) {
                for (int index = start; index <= end; index ++) {
                    sum += index;
                }
            } else {
                int temp = (start + end) / 2;
                ForkJoinSumTask left = new ForkJoinSumTask(start, temp);
                ForkJoinSumTask right = new ForkJoinSumTask(temp + 1, end);
                left.fork();
                right.fork();
                sum = left.join() + right.join();
            }
            return sum;
        }
    }
}
